package com.Lyoto.NetNotify.NetChecks.impl;

import com.Lyoto.NetNotify.Constraint.ExceptionEnum;
import com.Lyoto.NetNotify.Constraint.NetConfig;
import com.Lyoto.NetNotify.Exceptions.NetErrorException;
import com.Lyoto.NetNotify.NetChecks.Checker;
import com.Lyoto.NetNotify.Utils.NetUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author Lyoto
 * @Description 网络状态检查器
 * @Date 2022-09-19 17:52
 * @Version
 **/
@Slf4j
public class NetStatusChecker implements Checker {
    private static volatile NetStatusChecker checker;
    @Override
    public boolean isIpChanging() {
        try {
            String currentIp = NetUtil.getCurrentIp();
            log.info("检测IP是否变动|oldIp:{},currentIp:{},this ip change :{}",NetConfig.getIp(),currentIp,!(NetConfig.getIp().equals(currentIp)));
            return !(NetConfig.getIp().equals(currentIp));
        } catch (IOException e) {
            throw new NetErrorException(ExceptionEnum.FETCH_IP_ERROR);
        }
    }

    /**
     *  单例模式创建
     * @return checker 单例bean
     */
    public static NetStatusChecker singletonInstance(){
        if (checker == null){
            synchronized (NetStatusChecker.class){
                if (checker == null){
                    checker = new NetStatusChecker();
                    log.info("IPChecker装配|checker准备完毕，实例->{}",checker);
                }
            }
        }
        return checker;
    }
    
}
